package com.yu.demo.config.handler;

import com.yu.demo.commons.enums.ErrorResultEnum;
import com.yu.demo.commons.ex.ErrorHandler;
import com.yu.demo.commons.ex.UserException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 统一异常处理
 * @Author: WengYu
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 统一异常返回
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ErrorHandler makeException(Throwable e, HttpServletRequest request) {
        e.printStackTrace();
        return ErrorHandler.fail(ErrorResultEnum.SERVER_ERROR.getCode(),ErrorResultEnum.SERVER_ERROR.getMessage(), e);
    }

    /**
     * 对所有异常捕获
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ErrorHandler makeExcepton2(RuntimeException e, HttpServletRequest request) {
        e.printStackTrace();
        return ErrorHandler.fail(ErrorResultEnum.SERVER_ERROR.getCode(),e.getMessage(), e);
    }

    /**
     * User业务异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(UserException.class)
    public ErrorHandler businessException(UserException e, HttpServletRequest request) {
        e.printStackTrace();
        return ErrorHandler.fail(e.getCode(),e.getMessage(), e);
    }






}
